/**
 * Created with JetBrains PhpStorm.
 * User: root
 * Date: 22.05.13
 * Time: 19:07
 * To change this template use File | Settings | File Templates.
 */
(function($){
    $.fn.comments = function(options){
        $.getScript('js/wysibb/scriptAdmin.js',function(scr){
            $('html').find('head').append('<script type="text/javascript">'+scr+'</script>');
        });
        var settings = $.extend({
            'artTitle'        :' ',
            'parentdiv'       : '#tab',
            'childdiv'        : '#tabs',
            'progressStyleTop': '50%',
            'progressStyleLeft':'50%'
        }, options);

    var container = $(this);
    var aid = container.attr('id');
    //console.log(container);
        if(aid =='table'){
            aid = container.data('artId');
        }
        //console.log(aid);
        var div = $('<div>',{id:'progressbar',text:'Загрузка...',style:"top:"+settings.progressStyleTop+";left:"+settings.progressStyleLeft+";margin-left:-150px;margin-top:-30px;width:250px;height:15px;position:absolute;z-index:999;opacity;color:#FFFFFF;text-align:center;"});
        var td = $('<td>',{id:'progcont',colspan:2,'class':'ui-widget-content',style:'width:990px;height:160px;'});
        container.append(div);
        $(function(){
            $( "#progressbar" ).progressbar({value: false});
        });

        $("#progressbar")
            .ajaxStart(function(){ $('#progressbar').show();$(settings.childdiv).css('opacity',0.8);})
            .ajaxComplete(function(){$('div#progressbar').remove();});

    if(!$('body').data('container_'+aid)){

    $.get('/admin/comments/getpage',{id:1,artid:aid,limit:5},function(resp){

                    $(settings.parentdiv).hide();
                    var content = $(resp).not('script').filter('#content').children();//.find('div#backward,div#comment-container');
                    var scr = $(resp).filter('script');

                    $('#content').append(content);
                    init(aid);

                 if(!resp){
                        var maindiv = $('#comments-container');
                        maindiv.empty();
                        var div = $('<div>',{id:'message',title:'',text:'Комментариев нет',style:'font-size:16px;color:#FF0000'});
                        maindiv.append(div);
                        message('Сообщение','Комментариев нет','red');
                        }
        });
    }else if(aid == $('body').data('container_'+aid).i){
        console.info('elseif');
        console.log($('body').data('container_'+aid).i);
        var commP = $('div#commpagination').find('span.activepage');
        if(commP.length == 0){
            $('div#commpagination').find('span:first').attr('class','activepage');
        }
        var cid,comm,butDel;

        $(settings.childdiv).hide();
        $('div#comment-container').remove();

        var cont = $('body').data('container_'+aid).c;
        var back = $('body').data('container_'+aid).b;
       // var pag = $('body').data('container_'+aid).pagination;

        var txtArea = $(cont).find('textarea');

        var elP = $(cont).find('p#tdcomment');
        elP.each(function(i,p){
           if($(p).text() == ''){
              var txtAr_1 = $(p).parent().find('textarea:first');
              var txtAr_2 = $(p).parent().find('textarea:last');
               $(p).append(txtAr_2.html());
               txtAr_2.remove();
           }else{
               var txtAr = $(p).parent().find('textarea');
               if(txtAr.length  > 1){
                   $(p).parent().find('textarea:last').remove();
               }
           }
        });
        cont.each(function(i,elm){
           if($(elm).attr('data-artid') == aid){
                var el = $(elm).show();
               $('#content').prepend(el);
           }
        });
        $('#content').prepend(back);
        if($('div#comment-container').find('#commpagination span').length > 0){
            $('div#comment-container ').find('#commpagination').show();
        }

        var tr = $('#comment-container tbody tr');

        tr.each(function(i,elm){

             cid = $(elm).attr('id');
             comm = $(elm).find('td#comment_'+cid+' p').html();

            var butEdit = $('#editBut_'+cid).button({icons:{primary: "ui-icon-pencil"}}).click(function(){editComment($(this).parent().parent().attr('id'),comm)});
            var butVisib = $(elm).find('#button-visibility');
            if(butVisib.text() == 'Опубликован'){
                butVisib.css('background','#56a83c');
                butVisib.button({icons:{primary: "ui-icon-check"}});
            }else{
                butVisib.css('background','	#ffa500');
                butVisib.button({icons:{primary: "ui-icon-close"}});
            }
            butVisib.click(function(){visibilityComm($(elm).attr('id'))});
            var  butDel = $('#head_'+cid).find('.delbutton').button({icons:{primary: "ui-icon-trash"}}).click(function(){confirmDel('Подтверждение операций','Вы уверенны что хотите удалить комментарий ?',cid)});

        });
        $('#backward ').find('#buttonBack').button({icons:{primary: "ui-icon-arrowthick-1-w"}});
        $('#buttonBack').click(function(){
            if(openEditors()){
                buttonBack();
            }
        });
        var commpages = $('.commpage_current');
        commpages.click(function(){
            pageClick($(this),aid);
        });
    }

    function init(aid,pageid){
        console.info('init');
        var commcount = $('#commpages_'+aid).data('pagescount');

        var pagescount = Math.ceil(commcount/5);

        for(var p=1;p <= pagescount;p++){
            if(pagescount !==1){
                var segment = $('<span>',{class:'commpage_current'});
                $('div#commpagination').append(segment.text(p).attr('id',p)).show();
            }else{
                $('div#commpagination').hide();
            }
        }
        var cp = $('#commpagination');
        if(pageid == undefined){

            var activeP = cp.find('.activepage');
            if(activeP.length ==0 ){
                cp.find('span:first').attr('class','activepage');
            }
        }else{
              cp.find('span#'+pageid).attr('class','activepage');
        }
        var commpages = $('.commpage_current');
        commpages.click(function(){
            pageClick($(this),aid);
        });

        $('#backward ').find('#buttonBack').button({icons:{primary: "ui-icon-arrowthick-1-w"}}).click(function(){
           if(openEditors()){
               buttonBack();
           }
        }).end().find('span#title').append(settings.artTitle);
        var tr = $('#comment-container tbody tr');

        tr.each(function(i,elm){

            var cid = $(elm).attr('id');
            var td = $(elm).find('td#comment_'+cid);
            var tdHead = $(elm).find('td#head_'+cid);

            var butVisib = tdHead.find('#button-visibility');
            if(butVisib.text() == 'Опубликован'){
                butVisib.css('background','#56a83c');
                butVisib.button({icons:{primary: "ui-icon-check"}});
            }else{
                butVisib.css('background','	#ffa500');
                butVisib.button({icons:{primary: "ui-icon-close"}});
            }

            var comm = $(elm).find('td#comment_'+cid+' p').html();

            var txt = $('<textarea>',{id:'blog_comment_'+cid,style:'display:none'}).append(comm);

            var txtAr = $('<textarea>',{id:'blog_comment_'+cid,style:'display:none'}).append(comm);

                td.append(txtAr);
                var htmlCode = $(txt).wysibb().htmlcode();
                td.find('#tdcomment').html(htmlCode);

            butVisib.click(function(){visibilityComm(cid)});
            tdHead.find('#delbutton').button({icons:{primary: "ui-icon-trash"}}).click(function(){confirmDel('Подтверждение операций','Вы уверенны что хотите удалить комментарий ?',cid)});
            var editBut = $(elm).find('#editBut_'+cid).button({icons:{primary: "ui-icon-pencil"}}).click(function(){
                editComment(cid,comm);
            });
            var back = $('div#backward');
            var cont = $('div#comment-container');
            var pag = $('div#commpagination');
            $('body').data('container_'+aid,{b:back,c:cont,i:aid,pagination:pag});
        });
    }
    function getCache(page){
        console.info('getPage');
        var aid = $(page).parents('div#comment-container').data('artid');
        var commcount = $('.commpages').data('pagescount');
        var pagescount = Math.ceil(commcount/5);
        var commpages = $('.commpage_current');

        var aid = $(page).parents('div#comment-container').data('artid');
        $('#backward ').find('#buttonBack').button({icons:{primary: "ui-icon-arrowthick-1-w"}});
        var tr = $('#comment-container tbody tr');
        commpages.click(function(){
            pageClick($(this),aid);
        });
            tr.each(function(i,elm){

                var cid = $(elm).attr('id');
                var td = $(elm).find('td#comment_'+cid);
                var tdHead = $(elm).find('td#head_'+cid);
                var comm = $(elm).find('#tdcomment').html();

                var htmlCode = $('<textarea>',{'class':'blog_comment'}).append(comm).wysibb().htmlcode();
                var tar = $('<textarea>',{id:'blog_comment_'+cid,style:'display:none'}).append(comm);
                if(td.find('textarea').length ==0){
                    td.prepend(tar);
                    td.find('#tdcomment').empty().append(htmlCode);
                }

                var butVisib = tdHead.find('#button-visibility');
                if(butVisib.text() == 'Опубликован'){
                    butVisib.css('background','#56a83c');
                    butVisib.button({icons:{primary: "ui-icon-check"}});
                }else{
                    butVisib.css('background','	#ffa500');
                    butVisib.button({icons:{primary: "ui-icon-close"}});
                }

                $('#buttonBack').click(function(){
                    if(openEditors()){
                        buttonBack();
                    }
                });

                butVisib.click(function(){visibilityComm(cid)});
                tdHead.find('#delbutton').button({icons:{primary: "ui-icon-trash"}}).click(function(){confirmDel('Подтверждение операций','Вы уверенны что хотите удалить комментарий ?',cid)});
                var editBut = $(elm).find('#editBut_'+cid).button({icons:{primary: "ui-icon-pencil"}}).click(function(){
                    editComment(cid,comm);
                });
                var back = $('div#backward');
                var cont = $('div#comment-container');
                if(back.length > 1){
                    back.last().remove();
                }
                $('div#commpages').remove();
                $('body').data('container_'+aid,{b:back,c:cont,i:aid});
            });
    }
    function pageClick(page,aid){
        console.info('pageClick');
        var pageid = $(page).attr('id');

        if(!$('body').data('page_'+pageid)){
            progressBar('div#comment-container');
            $.get('/admin/comments/getpage',{id:pageid,artid:aid,limit:5},function(resp){
                $('div#comment-container,#backward,#commpages_'+aid).remove();
                var content = $(resp).filter('#content').children().show();

                $('#content').prepend(content).css('font-size','1em');
                $('body').data('page_'+pageid,$('div#comment-container'));
                init(aid,pageid);
            });

        }else{

            $('div#comment-container,#commpages_'+aid).remove();
            var pageCont = $('body').data('page_'+pageid);
            var content = pageCont.filter('#content').children().show();
           // console.log(pageCont);

            $('#content').find('#backward').after(pageCont.css('opacity',1));
            $('div#progressbar').hide();
           // $('#comment-container').css('opacity',1);
            getCache(page);
        }
    }
    function editComment(id,comment){
        var pageid = $(this).attr('id');
        var wbbOpt = {
            traceTextarea:true,
            lang:'ru',
            smileList:[
                {title:CURLANG.sm1, img: '<img src="{themePrefix}{themeName}/img/smiles/sm1.png" class="sm">', bbcode:":)"},
                {title:CURLANG.sm8 ,img: '<img src="{themePrefix}{themeName}/img/smiles/sm8.png" class="sm">', bbcode:":("},
                {title:CURLANG.sm1, img: '<img src="{themePrefix}{themeName}/img/smiles/sm2.png" class="sm">', bbcode:":D"},
                {title:CURLANG.sm3, img: '<img src="{themePrefix}{themeName}/img/smiles/sm3.png" class="sm">', bbcode:";)"},
                {title:CURLANG.sm4, img: '<img src="{themePrefix}{themeName}/img/smiles/sm4.png" class="sm">', bbcode:":up:"},
                {title:CURLANG.sm5, img: '<img src="{themePrefix}{themeName}/img/smiles/sm5.png" class="sm">', bbcode:":down:"},
                {title:CURLANG.sm6, img: '<img src="{themePrefix}{themeName}/img/smiles/sm6.png" class="sm">', bbcode:":shock:"},
                {title:CURLANG.sm7, img: '<img src="{themePrefix}{themeName}/img/smiles/sm7.png" class="sm">', bbcode:":angry:"},
                {title:CURLANG.sm9, img: '<img src="{themePrefix}{themeName}/img/smiles/sm9.png" class="sm">', bbcode:":sick:"}
            ],
            resize_maxheight:200,
            buttons: "bold,italic,underline,|,link,|,quote,smilebox"
        }

            var btnC,btnS,td;

            td = $('td#comment_'+id);

            td.find('p#tdcomment').hide();

            td.find('textarea').attr('class','blog_comment');

            td.find('button').remove();

            btnS = $('<button>',{id:'savecomment',text:'Сохранить',style:'float:right;margin:3px;font-size:10px'}).button({icons:{primary: "ui-icon-disk"}}).click(function(){confirmEdit(id,pageid)});
            btnC = $('<button>',{id:'cancelcomment',text:'Отмена',style:'float:right;margin:3px;font-size:10px'}).button({icons:{primary: "ui-icon-circle-close"}}).click(function(){closeEditor(id)});

            $('td#comment_'+id).append(btnC,btnS);
            $(".blog_comment").wysibb(wbbOpt);

        }

    function saveComm(cid){

        var td,div,wysibb,height,marginTop,bb,html;

        height = $('td#comment_'+cid).height();
        height = Math.round(height);
        marginTop = height/3;
        div = $('<div>',{id:'progressbar',style:'margin-top:'+marginTop+'px;'});
        wysibb = $('td#comment_'+cid).find('.wysibb');
        wysibb.hide();
        bb=$('#blog_comment_'+cid).bbcode();
        html = $('#blog_comment_'+cid).htmlcode();

        wysibb.parent().css({height:height+'px'}).append(div);
        $('td#comment_'+cid).find('button').remove();

        $(function(){
            $( "#progressbar" ).progressbar({value: false});
        });
        $("#progressbar")
            .ajaxStart(function(){
                    $(this).show();
            })
            .ajaxComplete(function(){
                $(this).hide();
            });

        if(bb !=''){
            $.ajax({
                url:'/admin/comments/update',
                dataType:'JSON',
                type:'POST',
                data:{id:cid,blog_comment:bb},
                success:function(resp){
                    message('Сохранение','Комментарий обновлен','green');
                    var p = $('<p>',{id:'tdcomment'}).append(html);
                    var tar = $('<textarea>',{id:'blog_comment_'+cid,style:'display:none'}).append(bb);
                    $('td#comment_'+cid).empty().append(p,tar);
                }
            });

        }else{
            message('Предупреждение','Ошибка, пустой комментарий');
        }
    }
    function visibilityComm(commId){

        var visib,btn,ico;
        btn = $('td#head_'+commId+'.ui-widget-content ').find('#button-visibility').find('.ui-button-text');

        if(btn.text() =='В черновике'){visib = 1;
        }else{visib = 1;}
        $.ajax({
            url:'/admin/comments/visibility',
            dataType:'JSON',
            type:'POST',
            data:{id:commId,visibility:visib},
            success:function(resp){

                ico = $('td#head_'+commId+'.ui-widget-content').find('#button-visibility').find('.ui-button-icon-primary');

                if(btn.text() == 'В черновике'){
                    btn.text('Опубликован');
                    ico.attr({'class':'ui-button-icon-primary ui-icon ui-icon-check',title:'Опубликован'});
                    btn.css({background:'#48a627'});
                }else{
                    btn.text('В черновике');
                    ico.attr({'class':'ui-button-icon-primary ui-icon ui-icon-close','title':'В черновике'});
                    btn.css({background:'#ffa500'});
                }
            }
        });
    }
    function deleteComm(cid){
        var tr = $('#tr'+cid);
        var aid = $('div#comment-container').data('artid');
        var tdHead = $('#head_'+cid);
        var tdContent = $('#comment_'+cid);
        $.ajax({
            url:'/admin/comments/comment-delete',
            dataType:'JSON',
            type:'POST',
            data:{id:cid},
            error:function(resp){message('Ошибка','Операция удаления не выполнена','red');},
            success:function(resp){
                message('Удаление','Комментарий успешно удален','green');
                tr.remove();
                tdHead.remove();
                tdContent.remove();
                $('tr#'+cid).remove();
                var tbody = $('div#comment-container tbody');
                var trLen = tbody.find('tr');

                var count = $('#commpages_'+aid).data('pagescount');
                var commcount = $('#commpages_'+aid).data('pagescount',parseInt(count)-1);
                if(trLen < 5 && commcount > 5){
                    var pgn = $('div#commpagination span');
                    pgn.find('.activepage').next().click();
                    pgn.find('.activepage').prev().click();
                }
                if(trLen.length == 0){
                    var span = $('div#commpagination');
                    span.find('span:last').remove();
                 //   var count = $('#commpages_'+aid).data('pagescount');
                 //   var commcount = $('#commpages_'+aid).data('pagescount',parseInt(count)-1);
                 //   console.log("count: ",count);
                 //   console.log("commcount: ",commcount);
                    var co = $('#content').find('#'+aid+' .comments').text(count-1);
                    $('div#commpagination span:last').click();
                    // comm.parentNode.removeChild(comm);
                }

            }
        });
    }
    function closeEditor(cid){

        var origComm,editor,txtarea;
        origComm = $('td#comment_'+cid+' textarea').html();
        txtarea = $('<textarea>',{id:'blog_comment'+cid,class:'blog_comment',rows:5,style:'display:none'}).append(origComm).wysibb().htmlcode();
        editor = $('td#comment_'+cid);
        //editor.html();
        $('td#comment_'+cid).find('div.wysibb').remove();
        var tar = $('<textarea>',{id:'blog_comment_'+cid,style:'display:none'}).append(origComm);
        $('td#comment_'+cid).append(tar);

        $('td#comment_'+cid).find('button#cancelcomment').hide().end().find('button#savecomment').hide();

        $('td#comment_'+cid).find('#tdcomment').show();
    }
    function message(title,text,color){
        var clr='#555555';
        if(color=='green'){clr='#006600';}
        if(color=='red'){clr='#cc0000';}
        var mes = $('<div>',{'title':title,'text':text,style:"text-align:center;padding:15px;color:"+clr});
        $(mes).dialog({
            resizable: false,
            height:140,
            modal: true,
            position:'center',
            buttons:{
                "Закрыть":function(){$(this).dialog('close');}
            },
            open: function(){
                $(this).parent().find('.ui-dialog-buttonpane button:first-child').button({
                    icons: { primary: 'ui-icon-circle-close' }
                });
            }
        });
    }
    function confirmDel(title,text,cid){
        $('<div>',{id:'confirm',title:title,text:text,style:'padding:20px;text-align:center;'}).dialog({
            resizable: false,
            height:160,
            modal: true,
            position:'center',
            buttons:{
                "Удалить":function(){deleteComm(cid);$(this).dialog('close');},
                "Закрыть":function(){$(this).dialog('close').remove();}
            },
            open: function(){
                $(this).parent().find('.ui-dialog-buttonpane button:first-child').button({
                    icons: { primary: 'ui-icon-trash' } }),
                    $(this).parent().find('.ui-dialog-buttonpane button:last-child').button({
                        icons: { primary: 'ui-icon-circle-close' }
                    });
            }

        });
    }
    function confirmEdit(id){
        $('<div>',{id:'confirm',title:'Подтверждение',text:'Обновить отредактированный комментарий ?',style:'padding:20px;text-align:center;overflow:hidden'}).dialog({
            resizable: false,
            height:140,
            modal: true,
            position:'center',
            buttons:{
                "Сохранить":function(){saveComm(id);$(this).dialog('close');},
                "Закрыть":function(){$(this).dialog('close');}
            },
            open: function(){
                $(this).parent().find('.ui-dialog-buttonpane button:first-child').button({
                    icons: { primary: 'ui-icon-disk' } }),
                    $(this).parent().find('.ui-dialog-buttonpane button:last-child').button({
                        icons: { primary: 'ui-icon-circle-close' }
                    });
            }
        });
    }
function progressBar(cont){
            var container = $(cont);
            var widthCont = container.width()/2;
            widthCont+='px';
            var aid = container.attr('id');
            var div = $('<div>',{id:'progressbar',text:'Загрузка...',style:"top:50%;left:50%;margin-left:-300px;margin-top:0px;width:250px;height:15px;position:absolute;z-index:999;opacity;color:#FFFFFF;text-align:center;"});
            var td = $('<td>',{id:'progcont',colspan:2,'class':'ui-widget-content',style:'width:990px;height:160px;'});
            container.append(div);

            $(function(){
                $( "#progressbar" ).progressbar({value: false});
            });
            $("#progressbar")
                .ajaxStart(function(){ $('#progressbar').show();$('div#comment-container').css('opacity',0.8);})
                .ajaxComplete(function(){$('div#progressbar').remove();});
            $('div#comment-container').css('opacity',1);
}
    function openEditors(){

        var openEditors = $('div#comment-container');
        var aid = openEditors.data('artid');
        var wysibb = openEditors.find('.wysibb');
            if(wysibb.length > 0){
                var id = wysibb.parents('tr').attr('id');
                confirmEdit(id);
            }else{
                return true;
            }
            return false;
    }
    function buttonBack(){
        var id = $('div#comment-container').data('artid')
        var commcount = $('#commpages_'+id).data('pagescount');
        $('div#comment-container').hide();
        $('#backward').remove();
        $(settings.childdiv).show().css('opacity',1);
        $(settings.parentdiv).show();
        $('#progressbar').remove();
        if(commcount > 0){
            $('table#table').find('tr#'+id+' span.commentcount').find('strong').text(commcount);
        }else{
            $('table#table').find('tr#'+id+' span.commentcount').text(commcount);
        }
    }
}
})(jQuery);